package com.vnaloha.common.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.vnaloha.common.model.User;
import com.vnaloha.common.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	private UserService userService;
	
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String addUser(@ModelAttribute("user") @Valid User user, BindingResult result, ModelMap modelMap) {
		
		if(result.hasErrors()) {
			modelMap.addAttribute("listUser", userService.listUser());
			return "signUpForm";
		} else {
			userService.addUser(user);
			return "redirect:/user";
		}
	}
	
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String updateUser(@ModelAttribute("user") @Valid User user, BindingResult result) {
		if(result.hasErrors()) {
			return "editUser";
		} else {
			userService.update(user);
			return "redirect:/user";
		}
	}
	
	@RequestMapping(method = RequestMethod.GET)
	public String displayUserForm(ModelMap modelMap) {
		modelMap.addAttribute("user", new User());
		modelMap.addAttribute("listUser", userService.listUser());
		return "signUpForm";
	}
	
	@RequestMapping("/delete/{userId}")
	public String deleteUser(@PathVariable("userId") Integer userId) {
		
		userService.removeUser(userId);
		return "redirect:/user";
	}
	
	@RequestMapping("/edit/{userId}")
	public String editUser(@PathVariable("userId") Integer userId, ModelMap modelMap) {
		User user = userService.getById(userId);
		if(null != user) {
			user.setPassword(null);
			modelMap.addAttribute("user", user);
			return "editUser";	
		} else {
			return "redirect:/user";
		}
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login() {
		return "user/login";
	}
	
	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public String register() {
		return "user/register";
	}

}
